package com.zsix.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.zsix.common.util.HttpClientUtil;
import com.zsix.common.util.SecurityUtil;
import com.zsix.common.util.StringUtils;
import com.zsix.system.mapper.SqlMapper;
import com.zsix.system.mapper.UserInfoMapper;
import com.zsix.system.service.IUserInfoService;
import com.zsix.common.entity.UserInfo;
import com.zsix.common.util.HttpsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    private String grant_type;
    @Value("${z6System.client_id}")
    private String client_id;
    @Value("${z6System.client_secret}")
    private String client_secret;
    @Value("${server.port}")
    private String port;

    @Value("${auto.client_id}")
    private String auto_clientid;
    @Value("${auto.client_secret}")
    private String auto_client_secret;
    @Value("${auto.redirect_uri}")
    private String auto_redirect_uri;
    @Value("${auto.sso_api_url}")
    private String auto_sso_api_url;
    @Value("${auto.authorize_url}")
    private String auto_authorize_url;

    /**
     * 获取token
     * @param username
     * @param password
     * @return
     */
    @Override
    public HashMap<String,Object> getToken(String username, String password) throws Exception{
        String url = "http://localhost:"+port+"/oauth/token?client_id="+client_id+""
                + "&client_secret="+client_secret+""
                + "&username="+username+"&password="+password+""
                + "&grant_type=password";

        //System.out.println("getToken:"+url);
        //增加header参数
        java.util.Map<String, String> headerMap = new Hashtable<String, String>();
        Base64 base64 = new Base64();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("charset", "utf-8");

        //请求返回信息json
        JSONObject json = null;
        String jsonData = HttpsUtils.post(url, headerMap, null);

        System.out.println("jsonData:"+jsonData);

        json = JSONObject.parseObject(jsonData);
        String access_token = json.getString("access_token");

        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("token",access_token);
        hashMap.put("refresh_token",json.getString("refresh_token"));

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        //AuthenticationContextHolder.setContext(authenticationToken);

        return hashMap;
    }
    @Override
    public HashMap<String,Object> Auto_Login(String code){
        try {
            HashMap<String, Object> map = new HashMap<>();
            final String text = auto_clientid + ":" + auto_client_secret;
            final byte[] textByte = text.getBytes("UTF-8");
            Base64 base64 = new Base64();
            String headrs = "Basic " + base64.encode(textByte);

            HashMap<String, String> headerMap = new HashMap<>();
            headerMap.put("Authorization", headrs);
            headerMap.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            String url = auto_authorize_url + "/oauth/token";
            System.out.println("oauth/token:"+url);
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("client_id", auto_clientid);
            hashMap.put("client_secret", auto_client_secret);
            hashMap.put("grant_type", "authorization_code");
            hashMap.put("code", code);
            hashMap.put("redirect_uri", auto_redirect_uri);
            System.out.println("body:"+hashMap.toString());
            String json = HttpClientUtil.doPost(url, hashMap, headerMap);
            System.out.println("json:"+json);
            if (StringUtils.isNull(json) == true) {
                String error = "err@获取json失败" + code + "," + auto_sso_api_url + "/oauth/token";
                map.put("state", 500);
                map.put("message", error);
                return map;
            }
            JSONObject jd = JSONObject.parseObject(json);

            Object token = jd.get("access_token");

            if (token != null) {
                headrs = "Bearer " + token;
                json = HttpClientUtil.doPost(auto_authorize_url + "/user/principal", hashMap, "Authorization", headrs); // 获取用户信息
                System.out.println("principal:"+json);
                if (StringUtils.isNull(json)) {
                    String error = "err@获取用户json失败" + code + "," + auto_sso_api_url + "/oauth/token";
                    map.put("state", 500);
                    map.put("message", error);
                    return map;
                }
                jd = JSONObject.parseObject(json);
                JSONObject userData = JSONObject.parseObject(jd.get("data").toString());
                Object userNo = userData.get("username");
                System.out.println("username:"+userNo);
                if (userNo == null) {
                    Object messgae = jd.get("msg");
                    String error = "err@获取人员信息失败:" + messgae.toString();
                    map.put("state", 500);
                    map.put("message", error);
                    return map;
                } else {
                    UserInfo userInfo = userInfoMapper.getUserInfo(userNo.toString());
                    map = getToken(userInfo.getUsername(), "admin123.");
                    map.put("username", userInfo.getUsername());
                    return map;
                }
            } else {
                String error = "err@获取人员信息失败:" + jd.get("msg").toString();
                map.put("state", 500);
                map.put("message", error);
                return map;
            }
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
            return new HashMap<>();
        }
    }
    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public HashMap<String,Object> loginAs(String username, String password){
        HashMap<String,Object> hashMap=new HashMap<>();
        UserInfo userInfo=userInfoMapper.getUserInfo(username);
        hashMap.put("username",userInfo.getUsername());
        hashMap.put("name",userInfo.getName());

        return hashMap;
    }
    @Override
    public HashMap<String,Object> refToken(String refresh_token){
        try {
            String url = "http://localhost:"+port+"/oauth/token?client_id="+client_id+""
                    + "&client_secret="+client_secret+"&refresh_token="+refresh_token+""
                    + "&grant_type=refresh_token";
            //增加header参数
            java.util.Map<String, String> headerMap = new Hashtable<String, String>();
            Base64 base64 = new Base64();
            headerMap.put("Content-Type", "application/json");
            headerMap.put("charset", "utf-8");

            //请求返回信息json
            JSONObject json = null;
            String jsonData = HttpsUtils.post(url, headerMap, null);

            json = JSONObject.parseObject(jsonData);
            String access_token = json.getString("access_token");

            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("token",access_token);
            hashMap.put("refresh_token",json.getString("refresh_token"));

            return hashMap;
        }
        catch (Exception ex){
            return null;
        }
    }
    /**
    根据用户名获取用户信息
     */
    @Override
    public UserInfo getUserInfo(String username){
        UserInfo userInfo=userInfoMapper.getUserInfo(username);
        if(userInfo==null)
            return null;
        return userInfoMapper.getUserInfo(username);
    }
    @Override
    public String Redirect_Login() {
        try {
            String url = auto_authorize_url + "/oauth/authorize?client_id=" + auto_clientid + "&redirect_uri=" + auto_redirect_uri + "&response_type=code&state=sycs";
            return url;
        }
        catch (Exception ex){
            return "err@"+ex.getMessage();
        }
    }
    @Override
    public String aotu_org(String token){
        String url=auto_sso_api_url + "/userManageApi/org/tree";
        String depts=HttpClientUtil.doGet(url,"","Authorization","bearer "+token);
        JSONObject deptJd = JSONObject.parseObject(depts);
        JSONArray deptList=deptJd.getJSONArray("data");
        Map<String, Object> param=new HashMap<>();
        if(deptList.size()>0){
            sqlMapper.delete("delete from sys_department",param);
        }
        for (int i = 0; i < deptList.size(); i++) {
            JSONObject list = deptList.getJSONObject(i);
            String sql="insert into sys_department(id,name,parentid,companyid) "
                    +"values('"+list.getString("orgId")+"','"+list.getString("orgName")+"'"
                    +",'"+list.getString("parentId")+"',2)";
            sqlMapper.insert(sql,param);

            String userUrl=auto_sso_api_url+"/userManageApi/orguser/list";
            HashMap<String,String> headerMap=new HashMap<>();
            headerMap.put("Authorization","bearer "+token);
            headerMap.put("X-Auth-Tenant","MTExMTEx");
            headerMap.put("X-Auth-User","NDQyMjU4NjU3OTg2MjUyOA==");
            headerMap.put("Content-Type","application/json;charset=utf-8");

            String orgType="{\"pageNo\":\"0\",\"pageSize\":\"1000\",\"orgId\":\""+list.getString("orgId")+"\"}";
            String json = HttpClientUtil.doPost(userUrl, orgType, headerMap);
            JSONObject userJd = JSONObject.parseObject(json);
            JSONObject empData = JSONObject.parseObject(userJd.getString("data"));
            JSONArray empList=empData.getJSONArray("records");

            for (int k = 0; k < empList.size(); k++) {
                JSONObject userList = empList.getJSONObject(k);
                if(userList.getString("userName").equals("admin"))
                {
                    sqlMapper.update("update sys_user set id='"+userList.getString("userId")+"' where username='admin'",param);
                    //sqlMapper.update("update sys_user set id='"+userList.getString("userId")+"' where username='admin'",param);
                }
                else{
                    sql="delete from sys_user where username='"+userList.getString("userName")+"'";
                    sqlMapper.delete(sql,param);
                    //插入人员
                    sql="insert into sys_user(id,name,username,password,tel) "
                            +"values('"+userList.getString("userId")+"','"+userList.getString("name")+"'"
                            +",'"+userList.getString("userName")+"','$2a$10$iFn3bNPUjlgqeabMqVeK/efvarrBMCXYBouEoEywLd.4.ewA/3cqK','"+userList.getString("phone")+"')";
                    sqlMapper.insert(sql,param);

                    //插入部门人员
                    sql="delete from sys_deptuser where username='"+userList.getString("userName")+"'";
                    sqlMapper.delete(sql,param);
                    sql="insert into sys_deptuser(id,username,departid) "
                            +"values('"+ UUID.randomUUID() +"'"
                            +",'"+userList.getString("userName")+"','"+list.getString("orgId")+"')";
                    sqlMapper.insert(sql,param);

                    sql="delete from sys_roleusers where username='"+userList.getString("userName")+"'";
                    sqlMapper.delete(sql,param);
                    //设置默认角色
                    if(list.getString("orgType").equals("0")) {
                        sql = "insert into sys_roleusers(id,username,roleid) "
                                + "values('" + UUID.randomUUID() + "'"
                                + ",'" + userList.getString("userName") + "','23c21b5e-f8c4-476c-a67c-ba0ab0675f6e')";

                    }
                    else{
                        sql = "insert into sys_roleusers(id,username,roleid) "
                                + "values('" + UUID.randomUUID() + "'"
                                + ",'" + userList.getString("userName") + "','c69e97fc-d305-46bf-be5e-6ac5f0c518a4')";

                    }
                    sqlMapper.insert(sql,param);
                }
            }
        }
        sqlMapper.update("update sys_department set parentId='0' where parentId='-1'",param);
        return "";
    }
}
